import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Form,
  Input,
  Space,
  Button,
  message,
  Modal,
  TreeSelect,
  Checkbox,
  Card,
  Row,
  Col,
  Upload,
} from 'antd';
import {
  LoadingOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  LeftOutlined,
} from '@ant-design/icons';
import { Link, connect } from 'umi';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import UploadUtil from '@/components/UploadUtil';

const { confirm } = Modal;

class ContentEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      cascaderOption: [],
      contentEditor: '',
      imageUrl: '',
      imgList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchCategory();
    console.log(this.props.location.query.id);
    if (this.props.location.query.id) {
      this.getData(this.props.location.query.id);
    }
  }
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id > 0) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: 'Article',
      }).then(() => {
        var result = this.props.response.result;
        result.contents = BraftEditor.createEditorState(result.contents);
        this.setState({ datas: result });
        if (result.imageUrl) {
          this.setState({ imageUrl: result.imageUrl });
        }

        this.formRef.current.setFieldsValue({ article: result });
      });
    }
  };
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'article' },
      })
      .then(() => {
        const resp = this.props.Category.response.result;
        // if (resp) {
        //   resp.forEach((item: any) => {
        //     const temp = item.value;
        //     item.value = item.title;
        //     item.title = item.title;
        //     if (item.children !== null) {
        //       item.children.forEach((ele: any) => {
        //         ele.value = ele.title;
        //       });
        //     }
        //   });
        // }

        this.setState({ cascaderOption: resp });
      });
  };
  onFinish = async (values: any) => {
    var act = 'Abp/create';
    if (values.article.id > 0) {
      act = 'Abp/update';
    }
    values.article.contents = this.state.contentEditor;

    if (this.state.imageUrl) {
      values.article.imageUrl = this.state.imageUrl;
    }
    this.props
      .dispatch({
        type: act,
        payload: values.article,
        control: 'Article',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id }, //this.props.response.id
        control: 'Article',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    console.log(editorState.toHTML());
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'done' && info.file.response) {
      this.setState({
        imageUrl: info.file.response.result,
      });
    }
  };
  render() {
    const { datas, imageUrl, loading } = this.state;
    const editorProps = {
      height: 120,
      onChange: this.handleChange,
    };
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <PageHeaderWrapper title={false}>
        <Form layout="vertical" ref={this.formRef} onFinish={this.onFinish}>
          <Card
            title="内容编辑"
            extra={
              <Space>
                <Button type="primary" htmlType="submit" loading={loading} key="1">
                  保存
                </Button>
                <Button key="2" onClick={this.ResetForm}>
                  重设
                </Button>
                <Button
                  key="3"
                  danger
                  onClick={this.showConfirm}
                  disabled={datas.id == 0 || !datas.id}
                >
                  删除
                </Button>
                <Link key="4" to="./content">
                  <Button type="dashed" icon={<LeftOutlined />}>
                    返回列表
                  </Button>
                </Link>
              </Space>
            }
          >
            <Row gutter={[30, 16]}>
              <Col span={18}>
                <div style={{ display: 'none' }}>
                  <Form.Item label="id" name={['article', 'id']}>
                    <Input />
                  </Form.Item>
                  <Form.Item label="imageUrl" name={['article', 'imageUrl']}>
                    <Input />
                  </Form.Item>
                </div>
                <Form.Item noStyle>
                  <Input.Group compact>
                    <Form.Item
                      name={['article', 'categoryId']}
                      label="所属分类"
                      rules={[{ required: true, message: '请选择分类' }]}
                    >
                      <TreeSelect
                        value={this.state.value}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        treeData={this.state.cascaderOption}
                        placeholder="请选择分类"
                        treeDefaultExpandAll
                        style={{ width: 380 }}
                      />
                    </Form.Item>
                    <Form.Item name={['article', 'tags']} label="标签">
                      <Input style={{ width: 380 }} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item noStyle>
                  <Input.Group compact>
                    <Form.Item
                      label="标题"
                      name={['article', 'title']}
                      rules={[{ required: true, message: '请输入标题' }]}
                    >
                      <Input style={{ width: 380 }} />
                    </Form.Item>
                    <Form.Item label="副标题" name={['article', 'subTitle']}>
                      <Input style={{ width: 380 }} placeholder="副标题，不超过50字符" />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item name={['article', 'summary']} label="概述">
                  <Input.TextArea />
                </Form.Item>
                <Form.Item
                  name={['article', 'contents']}
                  label="内容"
                  rules={[{ required: true, message: '请输入内容' }]}
                >
                  <BraftEditor style={{ border: '1px solid #ccc' }} {...editorProps} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="图片">
                  <Upload
                    action={UploadUtil.actionURL}
                    headers={{
                      Authorization: UploadUtil.accessToken,
                    }}
                    data={{
                      objectId: datas.id,
                      objectName: 'Article',
                      objectField: 'ImageUrl',
                    }}
                    name="files"
                    listType="picture-card"
                    showUploadList={false}
                    beforeUpload={UploadUtil.beforeUpload}
                    onChange={this.handleUpload}
                  >
                    {imageUrl ? (
                      <img
                        src={UploadUtil.imgServ + imageUrl}
                        style={{ width: '100%', height: '100%' }}
                      />
                    ) : (
                      uploadButton
                    )}
                  </Upload>
                </Form.Item>
                <Form.Item>
                  <Input.Group compact>
                    <Form.Item name={['article', 'isHot']} valuePropName="checked">
                      <Checkbox>热</Checkbox>
                    </Form.Item>
                    <Form.Item name={['article', 'isRec']} valuePropName="checked">
                      <Checkbox>推荐</Checkbox>
                    </Form.Item>
                    <Form.Item name={['article', 'isTop']} valuePropName="checked">
                      <Checkbox>置顶</Checkbox>
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
              </Col>
            </Row>
          </Card>
        </Form>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp, Article, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Article,
  Category,
}))(ContentEdit);
